# Create your views here.
from django.shortcuts import render
import requests
from lxml import etree
from django.http import HttpResponse
from django.views.decorators.csrf import csrf_exempt
from bs4 import BeautifulSoup
import json
from .models import XcSetting


def get_cooke():
    obj = XcSetting.objects.get(id=1)
    list = obj.list_cookie
    info = obj.info_cookie_field
    coupon = obj.coup_cookie
    gmap = obj.appkey_gmap
    return list, info, coupon, gmap


# get_cooke()[X]

# 携程列表
def code(request):
    city_code = request.GET.get("city_code")
    keywords = request.GET.get("keywords")
    pageIndex = request.GET.get("pageindex")
    url = 'https://m.ctrip.com/webapp/hotel/j/hotellistbody?pageid=212093&key=a02dCKMw8b7G*Bvv55%2B%7D9pFz1TJQek%3FI%C2%99%23qvDEEyaTv6LwKG94%5C.SHLvdce%24%C2%89EDu&huk=s8HysTKkheoFEGQWnYf8Y6ZEkYXMeZsEqXjUbWpYFNrc7e0XJ8Dx8YdUjt0w4fK5bj5YODx1kyobvnkjnY7bWlBYNtyfFj37WdheBmwzkj3cv3YfzvFDE1pY9neXMjDUe97wPfYPYFYGcv8metsYgsiLOYFYDYSFEnFKqkwtLiGTRBHj8rpDYBSJshyNrcaYmMWN0vgTx4Bek3YSdx3kxp3YGHik4wa4j4FE6nJtoWUHjprMdJ7NimZwsSvnlR7UjzbYAcjprDky3Oi4pwspRQ7E5PjmtxQTxs3EBPEodE6BWsteqhwzOEohjSGekhioZYslrO9eX8e3bxpqilHihSxaOWBNj8OetQwkPKq9wzkiQ5R43jAle1BEFzyqfvZliGcEtDy04v88K0fE8aK5Qw7Til6RAPjfrBDYOtJhcynrsljpDezBjQ7KsdjPHwDXxn9x6DxXzxboEszEF4EADWgnetDwDME0Pj76e6XipOYQcrB8EmDy7gvBXidsEPlykXvooKpOWotEUmjzcekAxFmjGrP1E9dWPbebhjolYsdj3qx7DxQfxpdxkXE47EZUE7kWosesaw7AEpSj0Qe5ciDPYpdrnBeGPe9dYzpEdAwgsWF0iddKNMEhTE5mEF7WGMeAhw5tEp3joneFPiAdYGdr3neagebZEPmYM3EfQwpbWasiaYdheL0y4zihXip6jpYNGyZhwBSYs0wFTyXMwMAYzZwzYmORfNw1FWDzvNmE6pW8kwnpjZGYL6RU1waPYdFY7Y5hyL4wzbEQ9r6sY7QjtNv8pIdfrOqi19Eb9ydtvhsY0XiTAjfYcgRDQwqUWbPjFdyOGRXpy17if8Wzaja7vhSw6tE8Y5PjmbwBLvz9jzYafRLfvb6YTNWAzePkRG8WzNjk3WTYdARUSvaGYD6WdHeBTRO3WAmEthWOY7tRdXw3aW8UvFBEStWP1wZ1jpTYf4RbSJoHwZ1'
    payloadheader = {
        'authority': 'm.ctrip.com',
        'method': 'POST',
        'path': '/webapp/hotel/j/hotellistbody?pageid=212093&key=a618c%60iDcf8%C2%A814KGaa035%2FJy2bddcaP%40e65d85d%3Fc61f44d399389006bebbc5cb&huk=S9aJ3pe7Te4PvAnwdYlfYp6E3YLpemkEn4jzaWaYs9jZmw0OJU0jAYoTjH9EbfvgbjMYL6Ia8wl5vAZwHYUcWQ7YTDyUljcSvdFeG1RHfj0leSYkSv0MKgkYGawb9jnke87yhZYtYmYnUvoMem0YHNidqYZYOY1pyDqjanx0PeGPwmMjMfrXgjNlR34iazwo9IU1Y9LjPYmse5LyShi9LiBGjUYoOyBpw8dYhFwFmy7fwakYmDwXY7BRqswTUWMAj9UJcqig6W4HYGdwDaRXUwazjoqRkYGsrQzjhGythw9OjfpjQ8wc8vhzRgOWktRAdyUQYkMiLARdgifYfmRDGw5DWq6JF5yfojHqRdtvFUw8GJ4QJlpYc8RUY6OjmbwApvMqjHYZPROkvzZY3PWaHePnRg8WmZj4AWAYPDRB4vtcY3TWQHeHpRqZWU6Ez6W6YD1RUMw8oW7Tjt0JFciGmW68YZFJt7RhsELSycz',
        'scheme': 'https',
        'accept': 'text/html',
        'accept-encoding': 'gzip, deflate, br',
        'accept-language': 'zh-CN,zh;q=0.9',
        'content-length': '1117',
        'content-type': 'application/json',
        'cookie':
            'HLDUUID=0b843e9e7ac647e28dc7c01380158f1b; supportwebp=true; list_hotel_price=%7B%22traceid%22%3A%22100004883-e7062867-8ccc-413e-a196-e7c1f235a92d%22%2C%22pageid%22%3A%22212093%22%2C%22searchcandidate%22%3A%7B%22person%22%3A0%2C%22bedtype%22%3A%22%22%2C%22breakfast%22%3A-1%2C%22childs%22%3A%5B%5D%2C%22segmentationno%22%3A0%2C%22showtype%22%3A0%7D%2C%22timestamp%22%3A1612575339558%2C%22minpriceroom%22%3A%7B%22roomid%22%3A213179330%2C%22isshadow%22%3A0%2C%22shadowId%22%3A0%2C%22avgprice%22%3A104%2C%22currency%22%3A%22RMB%22%2C%22iscanreserve%22%3A1%2C%22isusedcoupon%22%3A-1%2C%22isusedcashback%22%3A1%2C%22cashbackamount%22%3A0%2C%22couponamount%22%3A0%2C%22reductionamount%22%3A0%2C%22taxfee%22%3A0%7D%2C%22ttype%22%3A0%2C%22icp%22%3A0%2C%22ipd%22%3A0%2C%22isopenpricetolerate%22%3A1%2C%22passData%22%3A%7B%22minPriceDetailInfo%22%3A%22%22%7D%7D; JSESSIONID=FA725FE10C2A060C41F83F15202F1645; nfes_isSupportWebP=1; _RGUID=367fca6f-3a34-4768-b8e1-ace99577dcb7; _RDG=28593f7fbacef12d4d289d4c5e8c901290; _RSG=eT4Dwyco_P3tozTLcEhXZB; _bfi=p1%3D153002%26p2%3D153002%26v1%3D4%26v2%3D3; login_type=0; AHeadUserInfo=VipGrade=0&VipGradeName=%C6%D5%CD%A8%BB%E1%D4%B1&UserName=&NoReadMessageCount=1; IsNonUser=F; UUID=030BA967E51748ED94E2556CAEEB161B; IsPersonalizedLogin=T; GUID=09031094411806037866; _RF1=220.166.231.41; _bfs=1.1; MKT_Pagesource=H5; _ga=GA1.2.381500489.1613704700; _gid=GA1.2.233021318.1613704700; Union=OUID=&AllianceID=4897&SID=182042&SourceID=497&AppID=&OpenID=&exmktID=&createtime=1613705320&Expires=1614310120326; MKT_OrderClick=ASID=4897182042&AID=4897&CSID=182042&OUID=&CT=1613705320329&CURL=https%3A%2F%2Fm.ctrip.com%2Fhtml5%2F%3Fsourceid%3D497%26allianceid%3D4897%26sid%3D182042%26sepopup%3D150&VAL={"h5_vid":"1611048766529.2fzeni"}; login_uid=FAB0E054A70C6EEC632329916A79FE07; cticket=89C09FDBF2346C37547DE88D580880D807B4AC4CD50FE56EAEB49F20774DC812; ticket_ctrip=bJ9RlCHVwlu1ZjyusRi+ypZ7X2r4+yojsz/+cDJw4U11XpOuFbj86eyCOll4VAmaa8JxUV5L+tQptoD2MNQvsijCkVt9nGze8vjDb4nCQVO3x43ZTyepQ8bSTFHPgiMAL3/hLeEKAfcTGKGoNfT+1BY6FMFtFsmH1u60lRvwMUXd2O9b0gbJ9EzknkxtaMaChDHEJZ1PaXADr7tw+hEwWNQr5bRoatvhrOO7DK/Xol//8w9Gha0Kz8WDg6GmG73z2WwgewC5L9qhBVwtimZB+ibp3hlTBzBhIiMyopnr8Rw=; DUID=u=F12DAACC7ADB0C0EA81CFC3D87F455C8&v=0; librauuid=l4sgVFQafOA6CBpP; hotelhst=1164390341; _bfa=1.1611048766529.2fzeni.1.1613637341671.1613705950394.13.45.212093',
        'origin': 'https://m.ctrip.com',
        # 'referer': 'https://m.ctrip.com/webapp/hotel/guangzhou32/',
        'sec-fetch-dest': 'empty',
        'sec-fetch-mode': 'cors',
        'sec-fetch-site': 'same-origin',
        'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/87.0.4280.88 Safari/537.36',
        'x-ctrip-hotel-firend': '----',
        'x-requested-with': 'XMLHttpRequest'
    }
    payloadParam = {
        'abMaps': {},
        'adultCounts': 0,
        'business': 'false',
        # 'checkinDate': "20201221",
        # 'checkoutDate': "20201222",
        'cityID': city_code,
        'controlBitMap': 1,
        'costPerformanceHigh': 'false',
        'districtID': 0,
        'domesticHotelList': "domesticHotelList",
        'enableAdHotel': 'true',
        'filterItemList': [],
        'hiddenHotelIDList': [],
        'hiddenHotelIdListStr': "",
        'highestPrice': 0,
        'hotelIdList': [],
        'keyword': "",
        'keywordFilterItem': f"hotkeyword-{keywords}|||{keywords}|",
        'keywordText': "",
        'locationItemList': [],
        'lowestPrice': 0,
        'multipleHotel': 'false',
        'needLastPageRecommend': 'false',
        'notTopSet': 'false',
        'pageIndex': pageIndex,
        'pageSize': ' 20'
    }
    dumpJson = json.dumps(payloadParam)
    try:
        html = requests.post(url, data=dumpJson, headers=payloadheader)
        soup = BeautifulSoup(html.text, "html5lib")
        html_tree = etree.HTML(str(soup))
        hotel_code = html_tree.xpath('/html/body/div/@data-id')
        data_json = {
            'code': 200,
            'pageIndex': pageIndex,
            'hotel_id': hotel_code
        }
        return HttpResponse(json.dumps(data_json))
    except:
        return HttpResponse(json.dumps({'code': '400', 'ms': '被反爬了，联系管理员'}))


# 价格列表
def price_code(request):
    city_code = request.GET.get("city_code")
    keywords = request.GET.get("keywords")
    highestPrice = request.GET.get("highestprice")
    lowestPrice = request.GET.get("lowestprice")
    pageIndex = request.GET.get("pageindex")
    url = 'https://m.ctrip.com/webapp/hotel/j/hotellistbody?pageid=212093&key=a02dCKMw8b7G*Bvv55%2B%7D9pFz1TJQek%3FI%C2%99%23qvDEEyaTv6LwKG94%5C.SHLvdce%24%C2%89EDu&huk=s8HysTKkheoFEGQWnYf8Y6ZEkYXMeZsEqXjUbWpYFNrc7e0XJ8Dx8YdUjt0w4fK5bj5YODx1kyobvnkjnY7bWlBYNtyfFj37WdheBmwzkj3cv3YfzvFDE1pY9neXMjDUe97wPfYPYFYGcv8metsYgsiLOYFYDYSFEnFKqkwtLiGTRBHj8rpDYBSJshyNrcaYmMWN0vgTx4Bek3YSdx3kxp3YGHik4wa4j4FE6nJtoWUHjprMdJ7NimZwsSvnlR7UjzbYAcjprDky3Oi4pwspRQ7E5PjmtxQTxs3EBPEodE6BWsteqhwzOEohjSGekhioZYslrO9eX8e3bxpqilHihSxaOWBNj8OetQwkPKq9wzkiQ5R43jAle1BEFzyqfvZliGcEtDy04v88K0fE8aK5Qw7Til6RAPjfrBDYOtJhcynrsljpDezBjQ7KsdjPHwDXxn9x6DxXzxboEszEF4EADWgnetDwDME0Pj76e6XipOYQcrB8EmDy7gvBXidsEPlykXvooKpOWotEUmjzcekAxFmjGrP1E9dWPbebhjolYsdj3qx7DxQfxpdxkXE47EZUE7kWosesaw7AEpSj0Qe5ciDPYpdrnBeGPe9dYzpEdAwgsWF0iddKNMEhTE5mEF7WGMeAhw5tEp3joneFPiAdYGdr3neagebZEPmYM3EfQwpbWasiaYdheL0y4zihXip6jpYNGyZhwBSYs0wFTyXMwMAYzZwzYmORfNw1FWDzvNmE6pW8kwnpjZGYL6RU1waPYdFY7Y5hyL4wzbEQ9r6sY7QjtNv8pIdfrOqi19Eb9ydtvhsY0XiTAjfYcgRDQwqUWbPjFdyOGRXpy17if8Wzaja7vhSw6tE8Y5PjmbwBLvz9jzYafRLfvb6YTNWAzePkRG8WzNjk3WTYdARUSvaGYD6WdHeBTRO3WAmEthWOY7tRdXw3aW8UvFBEStWP1wZ1jpTYf4RbSJoHwZ1'
    payloadheader = {
        'authority': 'm.ctrip.com',
        'method': 'POST',
        'path': '/webapp/hotel/j/hotellistbody?pageid=212093&key=a618c%60iDcf8%C2%A814KGaa035%2FJy2bddcaP%40e65d85d%3Fc61f44d399389006bebbc5cb&huk=S9aJ3pe7Te4PvAnwdYlfYp6E3YLpemkEn4jzaWaYs9jZmw0OJU0jAYoTjH9EbfvgbjMYL6Ia8wl5vAZwHYUcWQ7YTDyUljcSvdFeG1RHfj0leSYkSv0MKgkYGawb9jnke87yhZYtYmYnUvoMem0YHNidqYZYOY1pyDqjanx0PeGPwmMjMfrXgjNlR34iazwo9IU1Y9LjPYmse5LyShi9LiBGjUYoOyBpw8dYhFwFmy7fwakYmDwXY7BRqswTUWMAj9UJcqig6W4HYGdwDaRXUwazjoqRkYGsrQzjhGythw9OjfpjQ8wc8vhzRgOWktRAdyUQYkMiLARdgifYfmRDGw5DWq6JF5yfojHqRdtvFUw8GJ4QJlpYc8RUY6OjmbwApvMqjHYZPROkvzZY3PWaHePnRg8WmZj4AWAYPDRB4vtcY3TWQHeHpRqZWU6Ez6W6YD1RUMw8oW7Tjt0JFciGmW68YZFJt7RhsELSycz',
        'scheme': 'https',
        'accept': 'text/html',
        'accept-encoding': 'gzip, deflate, br',
        'accept-language': 'zh-CN,zh;q=0.9',
        'content-length': '1117',
        'content-type': 'application/json',
        'cookie':
            'HLDUUID=0b843e9e7ac647e28dc7c01380158f1b; supportwebp=true; list_hotel_price=%7B%22traceid%22%3A%22100004883-e7062867-8ccc-413e-a196-e7c1f235a92d%22%2C%22pageid%22%3A%22212093%22%2C%22searchcandidate%22%3A%7B%22person%22%3A0%2C%22bedtype%22%3A%22%22%2C%22breakfast%22%3A-1%2C%22childs%22%3A%5B%5D%2C%22segmentationno%22%3A0%2C%22showtype%22%3A0%7D%2C%22timestamp%22%3A1612575339558%2C%22minpriceroom%22%3A%7B%22roomid%22%3A213179330%2C%22isshadow%22%3A0%2C%22shadowId%22%3A0%2C%22avgprice%22%3A104%2C%22currency%22%3A%22RMB%22%2C%22iscanreserve%22%3A1%2C%22isusedcoupon%22%3A-1%2C%22isusedcashback%22%3A1%2C%22cashbackamount%22%3A0%2C%22couponamount%22%3A0%2C%22reductionamount%22%3A0%2C%22taxfee%22%3A0%7D%2C%22ttype%22%3A0%2C%22icp%22%3A0%2C%22ipd%22%3A0%2C%22isopenpricetolerate%22%3A1%2C%22passData%22%3A%7B%22minPriceDetailInfo%22%3A%22%22%7D%7D; JSESSIONID=FA725FE10C2A060C41F83F15202F1645; nfes_isSupportWebP=1; _RGUID=367fca6f-3a34-4768-b8e1-ace99577dcb7; _RDG=28593f7fbacef12d4d289d4c5e8c901290; _RSG=eT4Dwyco_P3tozTLcEhXZB; _bfi=p1%3D153002%26p2%3D153002%26v1%3D4%26v2%3D3; login_type=0; AHeadUserInfo=VipGrade=0&VipGradeName=%C6%D5%CD%A8%BB%E1%D4%B1&UserName=&NoReadMessageCount=1; IsNonUser=F; UUID=030BA967E51748ED94E2556CAEEB161B; IsPersonalizedLogin=T; GUID=09031094411806037866; _RF1=220.166.231.41; _bfs=1.1; MKT_Pagesource=H5; _ga=GA1.2.381500489.1613704700; _gid=GA1.2.233021318.1613704700; Union=OUID=&AllianceID=4897&SID=182042&SourceID=497&AppID=&OpenID=&exmktID=&createtime=1613705320&Expires=1614310120326; MKT_OrderClick=ASID=4897182042&AID=4897&CSID=182042&OUID=&CT=1613705320329&CURL=https%3A%2F%2Fm.ctrip.com%2Fhtml5%2F%3Fsourceid%3D497%26allianceid%3D4897%26sid%3D182042%26sepopup%3D150&VAL={"h5_vid":"1611048766529.2fzeni"}; login_uid=FAB0E054A70C6EEC632329916A79FE07; cticket=89C09FDBF2346C37547DE88D580880D807B4AC4CD50FE56EAEB49F20774DC812; ticket_ctrip=bJ9RlCHVwlu1ZjyusRi+ypZ7X2r4+yojsz/+cDJw4U11XpOuFbj86eyCOll4VAmaa8JxUV5L+tQptoD2MNQvsijCkVt9nGze8vjDb4nCQVO3x43ZTyepQ8bSTFHPgiMAL3/hLeEKAfcTGKGoNfT+1BY6FMFtFsmH1u60lRvwMUXd2O9b0gbJ9EzknkxtaMaChDHEJZ1PaXADr7tw+hEwWNQr5bRoatvhrOO7DK/Xol//8w9Gha0Kz8WDg6GmG73z2WwgewC5L9qhBVwtimZB+ibp3hlTBzBhIiMyopnr8Rw=; DUID=u=F12DAACC7ADB0C0EA81CFC3D87F455C8&v=0; librauuid=l4sgVFQafOA6CBpP; hotelhst=1164390341; _bfa=1.1611048766529.2fzeni.1.1613637341671.1613705950394.13.45.212093',
        'origin': 'https://m.ctrip.com',
        'referer': 'https://m.ctrip.com/webapp/hotel/guangzhou32/',
        'sec-fetch-dest': 'empty',
        'sec-fetch-mode': 'cors',
        'sec-fetch-site': 'same-origin',
        'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/87.0.4280.88 Safari/537.36',
        'x-ctrip-hotel-firend': '----',
        'x-requested-with': 'XMLHttpRequest'
    }
    payloadParam = {
        'abMaps': {},
        'adultCounts': 0,
        'business': 'false',
        # 'checkinDate': "20201221",
        # 'checkoutDate': "20201222",
        'cityID': city_code,
        'controlBitMap': 1,
        'costPerformanceHigh': 'false',
        'districtID': 0,
        'domesticHotelList': "domesticHotelList",
        'enableAdHotel': 'true',
        'filterItemList': [],
        'hiddenHotelIDList': [],
        'hiddenHotelIdListStr': "",
        'highestPrice': highestPrice,
        'hotelIdList': [],
        'keyword': "",
        'keywordFilterItem': f"hotkeyword-{keywords}|||{keywords}|",
        'keywordText': "",
        'locationItemList': [],
        'lowestPrice': lowestPrice,
        'multipleHotel': 'false',
        'needLastPageRecommend': 'false',
        'notTopSet': 'false',
        'pageIndex': pageIndex,
        'pageSize': '10'
    }
    dumpJson = json.dumps(payloadParam)
    try:
        html = requests.post(url, data=dumpJson, headers=payloadheader)
        soup = BeautifulSoup(html.text, "html5lib")
        html_tree = etree.HTML(str(soup))
        hotel_code = html_tree.xpath('/html/body/div/@data-id')
        data_json = {
            'code': 200,
            'pageIndex': pageIndex,
            'hotel_id': hotel_code
        }
        return HttpResponse(json.dumps(data_json))
    except:
        return HttpResponse(json.dumps({'code': '400', 'ms': '被反爬了，联系管理员'}))



# 百度地图反坐标
def baidu_map_code(address):
    url = f'http://api.map.baidu.com/geocoding/v3/?address={address}&output=json&ak=6uWkk4NUY4BeGjMoa5dnGcYK84bcuPmK'
    html = requests.get(url)
    json_data = json.loads(html.text)
    lng = json_data['result']['location']['lng']
    lat = json_data['result']['location']['lat']

    data = {
        "lng": lng,
        "lat": lat
    }

    return data


# 高德地图坐标转百度地图
def geocv(xy):
    url = f'http://api.map.baidu.com/geoconv/v1/?coords={xy}&from=3&to=5&ak=6uWkk4NUY4BeGjMoa5dnGcYK84bcuPmK'
    html = requests.get(url)
    json_data = json.loads(html.text)
    lng = json_data['result'][0]['x']
    lat = json_data['result'][0]['y']
    data = {
        "lng": lng,
        "lat": lat
    }
    return data


# 地址(高德)经纬度查询
@csrf_exempt
def xiecheng_path(request):
    hotel_id = request.GET.get('hotel_id')
    html = requests.get(f'https://hotels.ctrip.com/hotels/detailPage?hotelId={hotel_id}')
    htmlz = etree.HTML(html.text)
    name = htmlz.xpath(".//*[@id='ibu-hotel-detail-head']/div[1]/div[1]/div[1]/h1/text()")[0]
    path = htmlz.xpath(".//*[@id='ibu-hotel-detail-head']/div[1]/div[1]/div[2]/div[1]/span/span[1]/text()")[0]
    coordinate = baidu_map_code(path)
    data = {
        "code": 200,
        "hotel_id": hotel_id,
        "name": name,
        "path": path,
        "coordinate": coordinate
    }

    return HttpResponse(json.dumps(data))


#  携程APP报价查询
def hotel_price(request):
    check_in = request.GET.get('check_in')  # 按照此格式 2021/01/12
    check_out = request.GET.get('check_out')
    hotel_id = request.GET.get('hotel_id')
    key = 'Sd1@sdMDKS%sdsokGS*mL&sdLLOp'
    header = {
        'Host': 'm.ctrip.com',
        'Connection': 'keep-alive',
        'Cache-Control': 'max-age=0',
        'sec-ch-ua': '"Google Chrome";v="87","Not;A Brand";v="99","Chromium";v="87"',
        'sec-ch-ua-mobile': '?0',
        'Upgrade-Insecure-Requests': '1',
        'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/87.0.4280.88 Safari/537.36',
        'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9',
        'Sec-Fetch-Site': 'none',
        'Sec-Fetch-Mode': 'navigate',
        'Sec-Fetch-User': '?1',
        'Sec-Fetch-Dest': 'document',
        'Accept-Encoding': 'gzip, deflate, br',
        'Accept-Language': 'zh-CN,zh;q=0.9',
        'Cookie':
            'HLDUUID=0b843e9e7ac647e28dc7c01380158f1b; supportwebp=true; list_hotel_price=%7B%22traceid%22%3A%22100004883-e28ff310-64da-4fe7-b065-f3a2e8d42d7f%22%2C%22pageid%22%3A%22212093%22%2C%22searchcandidate%22%3A%7B%22person%22%3A0%2C%22bedtype%22%3A%22%22%2C%22breakfast%22%3A-1%2C%22childs%22%3A%5B%5D%2C%22segmentationno%22%3A0%2C%22showtype%22%3A0%7D%2C%22timestamp%22%3A1613706009059%2C%22minpriceroom%22%3A%7B%22roomid%22%3A136804360%2C%22isshadow%22%3A0%2C%22shadowId%22%3A0%2C%22avgprice%22%3A308%2C%22currency%22%3A%22RMB%22%2C%22iscanreserve%22%3A1%2C%22isusedcoupon%22%3A-1%2C%22isusedcashback%22%3A1%2C%22cashbackamount%22%3A0%2C%22couponamount%22%3A0%2C%22reductionamount%22%3A0%2C%22taxfee%22%3A0%7D%2C%22ttype%22%3A0%2C%22icp%22%3A0%2C%22ipd%22%3A0%2C%22isopenpricetolerate%22%3A1%2C%22passData%22%3A%7B%22minPriceDetailInfo%22%3A%22%22%7D%7D; JSESSIONID=99A1AAD7B9CE2C987C2D30F0E636996F; nfes_isSupportWebP=1; _RGUID=367fca6f-3a34-4768-b8e1-ace99577dcb7; _RDG=28593f7fbacef12d4d289d4c5e8c901290; _RSG=eT4Dwyco_P3tozTLcEhXZB; _bfi=p1%3D153002%26p2%3D153002%26v1%3D4%26v2%3D3; login_type=0; AHeadUserInfo=VipGrade=0&VipGradeName=%C6%D5%CD%A8%BB%E1%D4%B1&UserName=&NoReadMessageCount=1; IsNonUser=F; UUID=030BA967E51748ED94E2556CAEEB161B; IsPersonalizedLogin=T; GUID=09031094411806037866; _RF1=220.166.231.41; _bfs=1.1; MKT_Pagesource=H5; _gid=GA1.2.233021318.1613704700; _ga=GA1.2.381500489.1613704700; Union=OUID=&AllianceID=4897&SID=182042&SourceID=497&AppID=&OpenID=&exmktID=&createtime=1613705320&Expires=1614310120326; MKT_OrderClick=ASID=4897182042&AID=4897&CSID=182042&OUID=&CT=1613705320329&CURL=https%3A%2F%2Fm.ctrip.com%2Fhtml5%2F%3Fsourceid%3D497%26allianceid%3D4897%26sid%3D182042%26sepopup%3D150&VAL={"h5_vid":"1611048766529.2fzeni"}; login_uid=FAB0E054A70C6EEC632329916A79FE07; cticket=89C09FDBF2346C37547DE88D580880D807B4AC4CD50FE56EAEB49F20774DC812; ticket_ctrip=bJ9RlCHVwlu1ZjyusRi+ypZ7X2r4+yojsz/+cDJw4U11XpOuFbj86eyCOll4VAmaa8JxUV5L+tQptoD2MNQvsijCkVt9nGze8vjDb4nCQVO3x43ZTyepQ8bSTFHPgiMAL3/hLeEKAfcTGKGoNfT+1BY6FMFtFsmH1u60lRvwMUXd2O9b0gbJ9EzknkxtaMaChDHEJZ1PaXADr7tw+hEwWNQr5bRoatvhrOO7DK/Xol//8w9Gha0Kz8WDg6GmG73z2WwgewC5L9qhBVwtimZB+ibp3hlTBzBhIiMyopnr8Rw=; DUID=u=F12DAACC7ADB0C0EA81CFC3D87F455C8&v=0; librauuid=l4sgVFQafOA6CBpP; hotelhst=1164390341; _bfa=1.1611048766529.2fzeni.1.1613637341671.1613706001667.13.46.212094'

    }
    html_api = requests.get(
        f'https://m.ctrip.com/webapp/hotel/hoteldetail/rooms/{hotel_id}?inday={check_in}&outday={check_out}&key={key}'
        , headers=header
    )
    html_data = etree.HTML(html_api.text)
    data_data = html_data.xpath("/html/body/input/@data-roomlistinfo")[0]
    # data_datat = html_data.xpath("/html/body/input/@data-roomextinfo")[0]
    data_json = json.loads(data_data)
    rooms = data_json['rooms']
    hotels = []
    for room in rooms:
        fullname = room['fullName']
        name = room['name']
        price = room['priceInfo']['cnyPrice']
        breakfast = room['breakfast']
        try:
            servicetags = room['servicetags'][0]['description'].split('>')[1].split('<')[0]
        except:
            servicetags = None
        try:
            mark = room['servicetags'][0]['mark'].split('>')[1].split('<')[0]
        except:
            mark = None
        bid = room['bid']
        id = room['id']

        hotels.append({'fullname': fullname,
                       'name': name,
                       'price': price,
                       'breakfast': breakfast,
                       'servicetags': servicetags,
                       'mark': mark,
                       'bid': bid,
                       'ids': id})

    json_data = {
        'code': 200,
        'room': [hotel for hotel in hotels]
    }

    return HttpResponse(json.dumps(json_data))


# 携程酒店优惠卷查询
def coupon(request):
    check_in = request.GET.get('check_in')  # 格式 20210114
    check_out = request.GET.get('check_out')
    hotel_id = request.GET.get('hotel_id')
    payloadheader = {
        'authority': 'm.ctrip.com',
        'method': 'POST',
        'path': '/webapp/hotel/api/getallcoupon?pageid=212094',
        'scheme': 'https',
        'accept': 'application/json',
        'accept-encoding': 'gzip, deflate, br',
        'accept-language': 'zh-CN,zh;q=0.9',
        'content-length': '113',
        'content-type': 'application/json',
        'cookie':
            'HLDUUID=ad39f751daa145459c544ba3bebfcfca; supportwebp=true; list_hotel_price=%7B%22traceid%22%3A%22100004883-18d1041c-418a-4f88-91da-2805f6cc16c0%22%2C%22pageid%22%3A%22212093%22%2C%22searchcandidate%22%3A%7B%22person%22%3A0%2C%22bedtype%22%3A%22%22%2C%22breakfast%22%3A-1%2C%22childs%22%3A%5B%5D%2C%22segmentationno%22%3A0%2C%22showtype%22%3A0%7D%2C%22timestamp%22%3A1614758644215%2C%22minpriceroom%22%3A%7B%22roomid%22%3A836364487%2C%22isshadow%22%3A0%2C%22shadowId%22%3A0%2C%22avgprice%22%3A889%2C%22currency%22%3A%22RMB%22%2C%22iscanreserve%22%3A1%2C%22isusedcoupon%22%3A-1%2C%22isusedcashback%22%3A1%2C%22cashbackamount%22%3A0%2C%22couponamount%22%3A0%2C%22reductionamount%22%3A0%2C%22taxfee%22%3A0%7D%2C%22ttype%22%3A0%2C%22icp%22%3A0%2C%22ipd%22%3A0%2C%22isopenpricetolerate%22%3A1%2C%22passData%22%3A%7B%22minPriceDetailInfo%22%3A%22%22%7D%7D; JSESSIONID=F0EAF140E379EA1B2C0F609D5569FBFC; nfes_isSupportWebP=1; _RGUID=367fca6f-3a34-4768-b8e1-ace99577dcb7; _RDG=28593f7fbacef12d4d289d4c5e8c901290; _RSG=eT4Dwyco_P3tozTLcEhXZB; login_type=0; AHeadUserInfo=VipGrade=0&VipGradeName=%C6%D5%CD%A8%BB%E1%D4%B1&UserName=&NoReadMessageCount=1; IsNonUser=F; IsPersonalizedLogin=T; UUID=030BA967E51748ED94E2556CAEEB161B; GUID=09031094411806037866; _ga=GA1.2.381500489.1613704700; login_uid=FAB0E054A70C6EEC632329916A79FE07; cticket=89C09FDBF2346C37547DE88D580880D807B4AC4CD50FE56EAEB49F20774DC812; ticket_ctrip=bJ9RlCHVwlu1ZjyusRi+ypZ7X2r4+yojsz/+cDJw4U11XpOuFbj86eyCOll4VAmaa8JxUV5L+tQptoD2MNQvsijCkVt9nGze8vjDb4nCQVO3x43ZTyepQ8bSTFHPgiMAL3/hLeEKAfcTGKGoNfT+1BY6FMFtFsmH1u60lRvwMUXd2O9b0gbJ9EzknkxtaMaChDHEJZ1PaXADr7tw+hEwWNQr5bRoatvhrOO7DK/Xol//8w9Gha0Kz8WDg6GmG73z2WwgewC5L9qhBVwtimZB+ibp3hlTBzBhIiMyopnr8Rw=; DUID=u=F12DAACC7ADB0C0EA81CFC3D87F455C8&v=0; librauuid=5qFfS2a8U8Pc2hdn; _RF1=222.210.137.121; _abtest_userid=4b579c08-e73c-4cc0-8453-ede9e047492d; ibulanguage=CN; ibulocale=zh_cn; cookiePricesDisplayed=CNY; _gid=GA1.2.204157228.1614586165; MKT_OrderClick=ASID=4897155952&AID=4897&CSID=155952&OUID=index&CT=1614586164895&CURL=https%3A%2F%2Fwww.ctrip.com%2F%3Fsid%3D155952%26allianceid%3D4897%26ouid%3Dindex&VAL={"pc_vid":"1611048766529.2fzeni"}; MKT_CKID=1614586164923.db2bf.x31i; MKT_Pagesource=PC; HotelCityID=692split%E9%98%B3%E6%B1%9FsplitYangjiangsplit2021-3-1split2021-03-02split0; MKT_CKID_LMT=1614674317125; Union=AllianceID=4897&SID=130026&OUID=&createtime=1614675731&Expires=1615280530657; Session=smartlinkcode=U130026&smartlinklanguage=zh&SmartLinkKeyWord=&SmartLinkQuary=&SmartLinkHost=; intl_ht1=h4=213_28756749,17_8719620,100_67227142,30_5374561,30_1284920,278_28680123; _uetsid=7407a1407a6511eb8d22971c1fc4f9d1; _uetvid=7407ff207a6511eb94bc4965d2bf1df1; _bfi=p1%3D102003%26p2%3D102003%26v1%3D228%26v2%3D226; _jzqco=%7C%7C%7C%7C1614674317298%7C1.1505163905.1614586164920.1614756744568.1614756782345.1614756744568.1614756782345.0.0.0.169.169; __zpspc=9.9.1614756643.1614756782.6%232%7Cwww.baidu.com%7C%7C%7C%7C%23; appFloatCnt=168; hotelhst=1164390341; _bfa=1.1611048766529.2fzeni.1.1614751745879.1614758668070.26.231.212094',
        'origin': 'https://m.ctrip.com',
        'referer': 'https://m.ctrip.com/webapp/hotel/hoteldetail/51950471.html?atime=20210111&daylater=0&days=1&contrl=0&pay=0&discount=&latlon=&listindex=10&userLocationSearch=false&lastCoupon=872646720',
        'sec-fetch-dest': 'empty',
        'sec-fetch-mode': 'cors',
        'sec-fetch-site': 'same-origin',
        'user-agent': 'Mozilla/5.0 (iPhone; CPU iPhone OS 13_2_3 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/13.0.3 Mobile/15E148 Safari/604.1',
        'x-ctrip-hotel-firend': '----',
        'x-requested-with': 'XMLHttpRequest'
    }
    payloadParam = {
        # 'adultNum': '2',
        'checkinDate': check_in,
        'checkoutDate': check_out,
        # 'childNum': 0,
        # 'destCityId': '32',
        'hotelId': hotel_id
    }
    url = 'https://m.ctrip.com/webapp/hotel/api/getallcoupon?pageid=212094'
    dumpJson = json.dumps(payloadParam)
    html = requests.post(url, data=dumpJson, headers=payloadheader)
    try:
        json_data = json.loads(html.text)
        id = json_data[0]["id"]
        name = json_data[0]['name']
        start_time = json_data[0]['startTime']
        end_time = json_data[0]['endTime']
        start_amount = json_data[0]['deductionList'][0]['startAmount']
        deduction_amount = json_data[0]['deductionList'][0]['deductionAmount']

        json_data = {
            'id': id,
            'name': name,
            'start_time': start_time,
            'end_time': end_time,
            'start_amount': start_amount,
            'deduction_amount': deduction_amount
        }
        return HttpResponse(json.dumps(json_data))
    except:
        return HttpResponse(json.dumps({'code': 200, 'msg': '无优惠卷'}))
